<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <a href="https://wylt.com/r/1650784801317" class="btn btn-primary mt-3">进入备用聊天室</a>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
</head>
<body>
<div class="container mt-4">
    <h2>聊天室</h2>
    <div id="chat-box" class="border p-3 mb-3" style="height:300px;overflow-y:auto;"></div>
    <form id="chat-form">
        <div class="input-group">
            <input type="text" id="message" class="form-control" placeholder="输入消息..." autocomplete="off">
            <button class="btn btn-primary" type="submit">发送</button>
        </div>
    <p>此bug已修复</p>
    </form>
    <a href="/" class="btn btn-link mt-3">返回首页</a>
</div>
<script>
    var socket = io();
    var username = "{{ username }}";
    var chatBox = document.getElementById('chat-box');
    document.getElementById('chat-form').onsubmit = function(e) {
        e.preventDefault();
        var msg = document.getElementById('message').value;
        if(msg.trim() !== ''){
            socket.emit('send_message', {username: username, message: msg});
            document.getElementById('message').value = '';
        }
    };
    socket.on('receive_message', function(data){
        var div = document.createElement('div');
        div.id = `message-${data.id}`;
        div.className = 'message-container mb-2';
        div.innerHTML = `
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    ${data.username}: ${data.message}
                    <small class="text-muted ms-2">${new Date(data.timestamp).toLocaleTimeString()}</small>
                </div>
                <button class="btn btn-sm btn-outline-danger recall-btn" 
                        data-message-id="${data.id}"
                        style="display: ${data.sender === username ? 'block' : 'none'}">
                    撤回
                </button>
            </div>
        `;
        chatBox.appendChild(div);
        chatBox.scrollTop = chatBox.scrollHeight;
    });

    // 处理消息撤回事件
    socket.on('message_recalled', function(data) {
        const messageDiv = document.getElementById(`message-${data.message_id}`);
        if (messageDiv) {
            messageDiv.innerHTML = `
                <div class="text-muted">
                    <i>消息已撤回</i>
                </div>
            `;
        }
    });

    // 撤回消息
    chatBox.addEventListener('click', function(e) {
        if (e.target.classList.contains('recall-btn')) {
            const messageId = e.target.dataset.messageId;
            socket.emit('recall_message', {
                message_id: messageId,
                username: username
            });
        }
    });
</script>
</body>
</html>
